package area

import (
	"context"
	dto "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/dto/base"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/base/area"
)

type areaService struct {
	areaRepo area.AreaConfigRepositoryIface
}

// NewAreaService 构造函数
func NewAreaService(areaRepo area.AreaConfigRepositoryIface) AreaServiceIface {
	return &areaService{areaRepo: areaRepo}
}

func (s *areaService) AreaTree(ctx context.Context) ([]*dto.AreaItem, error) {
	areaList, err := s.areaRepo.AreaConfigList(ctx)
	if err != nil {
		return nil, nil
	}

	list := make([]*dto.AreaItem, 0)
	for _, item := range areaList {
		list = append(list, &dto.AreaItem{
			Id:           item.Id,
			DisplayOrder: item.DisplayOrder,
			ItemCode:     item.ItemCode,
			ItemName:     item.ItemName,
			NormName:     item.NormName,
			ParentCode:   item.ParentCode,
			Children:     nil,
		})
	}

	trees := s.buildTrees(list)
	return trees, nil
}

// BuildTrees 构建多棵树
func (s *areaService) buildTrees(nodes []*dto.AreaItem) []*dto.AreaItem {
	nodeMap := make(map[string]*dto.AreaItem)

	// 创建节点映射
	for _, nd := range nodes {
		nodeMap[nd.ItemCode] = nd
	}

	// 构建树结构
	var trees []*dto.AreaItem
	for _, nd := range nodes {
		if nd.ParentCode == "0" {
			trees = append(trees, nd)
		} else {
			parent, ok := nodeMap[nd.ParentCode]
			if ok {
				parent.Children = append(parent.Children, nd)
			}
		}
	}

	return trees
}
